const db = require('../models/db')
const moment = require('moment')
const {imgPath} = require('../public/js/common')

//展示指定comment_id下的所有回复
exports.list =async (comment_id,next) => {
  try{
    // console.log(next);
    // console.log(comment_id);
    // const {comment_id} = req.query;
    const sqlStr = `
    SELECT * FROM replies WHERE comment_id=${comment_id}
    `;
    const replies = await db.query(sqlStr);
    replies.forEach((item)=>{
      item.create_time = moment(item.create_time).format("YYYY-MM-D HH:mm:ss")
    });
    // res.status(201).json(replies)
    return replies;
  }catch (err) {
    next(err)

  }
};
//创建一条新的回复
exports.create =async (req,res,next)=>{
  const {comment_id,from_id,from_nickname,to_id,to_nickname,reply_content} = req.body;
  console.log(req.body);
  const create_time = moment().format("YYYY-MM-D HH:mm:ss");
  const sqlStr=
      `INSERT INTO replies(comment_id,from_id,from_nickname,to_id,to_nickname,reply_content,create_time)
         VALUES('${comment_id}',
                '${from_id}',
                '${from_nickname}',
                '${to_id}',
                '${to_nickname}',
                '${reply_content}',
                '${create_time}')`;

  try{
    const result = await db.query(sqlStr);
    console.log(result);
    const [reply] = await db.query(`SELECT * FROM replies WHERE id = ${result.insertId}`)
    reply.create_time =moment(reply.create_time).format("YYYY-MM-D HH:mm:ss")
    res.status(201).json(reply)
  }catch (err) {
    next(err)
  }
};

exports.destroy = async (req,res,next)=>{
  //获取请求体,拿到当前需要被删除的子评论的id
  const {id} = req.params;

  //根据当前id去删除对应的话题
  const sqlStr =
      `DELETE FROM replies 
       where id=${id}`;
  //执行sql语句
  const result = await db.query(sqlStr);
  console.log(result);
  //删除成功之后，返回空对象
  res.status(201).json({})
};
